var selData = [];
var API1;
layui.use(['form', 'table','tfApi','jquery'], function () {
    var $ = layui.jquery, API = layui.tfApi;
    API1=API;
    var myDate = new Date;
    var year = myDate.getFullYear(); //获取当前年
    var mon = myDate.getMonth() + 1; //获取当前月
    var date = myDate.getDate(); //获取当前日

    var _curl = window.location.href,
        _str = _curl.split("?")[1],
        serviceId = _str.split("&")[0],
        _amounts = _str.split("&")[1],
        sellerId = _str.split("&")[2],
        infoUrl = API.invoice.qryInvoiceInfo,
        sjrUrl = API.invoice.qryConsignee;

    console.log("_amounts===+"+_amounts+"serviceId=="+serviceId);

    $(".applyTime").html(year + "-" + mon + "-" + date);

    $("#invoiceAmount").attr('data-amount',_amounts);

    //$(".xxje").html("￥"+_amounts+'.00');

    //$(".dxje").html(infCaps(_amounts));
    //新增收件人
    $(".addAdse").click(function () {
      //  var _url = '/flexible_merchant/index.html?#/page/invoice/addressee.html';
      //   var _url = '/index.html#/page/invoice/addressee.html';
      //   console.log("url ="+ window.parent.location.href);
      //   window.parent.parent.location.href = _url;
      //   window.parent.parent.location.reload();
        var index = layer.open({
            title: '添加收件人',
            type: 2,
            shade: 0.2,
            maxmin:true,
            shadeClose: true,
            area: ['100%', '100%'],
            content: '../../page/invoice/userInfo.html',
            success: function (layero, index) {
                var frameId = $(layero).find('iframe').attr("id");
                //找到子页面的document对象
                var document = window.frames[frameId].document;
                //根据id找到子页面中相应的元素并赋值recivePersonId
                $(document).find("input[name='recivePersonId']").val('');
                //从申请发票页面添加收件人
                $(document).find("input[name='addFromApply']").val('apply');
            },
            end:function(){
                // location.reload();
                // window.parent.parent.location.reload();
                layui.close(index);
            }
        });
        $(window).on("resize", function () {
            layer.full(index);
        });
        return false;
    });


    var roleHtml = '';

    $.ajax({
        url : API.CURL + "/seller/qryServiceType",
        type : "post",
        data : {
            sellerId : sellerId
        },dataType : "json",
        success : function(res){
            //清空数据
            document.getElementById('role_id').innerHTML  = "";

            var arr = res.data.split(",");

            for(var i = 0;i<arr.length;i++){
                var arr_ = arr[i].split("*");
                roleHtml += "<label class='ui-flex' style='padding:10px 0;cursor: pointer;text-align: left;'>" +
                                "<div style='padding:14px 10px 0 0;'><input type='radio' name='invoiceContent' style='width: auto;' value='"+arr[i]+"'></div>" +
                                "<div>" +
                                    "<b>"+arr_[1]+"</b>" +
                                    "<p style='padding-top:4px;'>"+arr_[0]+"</p>" +
                                "</div>" +
                            "</label>";
            }

            //渲染数据
            document.getElementById('role_id').innerHTML  = roleHtml;
        }
    });

    API.postAjax(infoUrl,{serviceId:serviceId},function (res) {
        if(res.code == 0){
            $("#gmf").html(res.data.sellerInfo.sellerCompanyName);
            $("#sh").val(res.data.sellerInfo.taxPayerCode);
            $("#dz").val(res.data.sellerInfo.sellerAddress + "-" + res.data.sellerInfo.sellerPhone);
            $("#yh").val(res.data.sellerInfo.sellerBank  + "-" + res.data.sellerInfo.sellerBankAccount);


            $("#xsf").html(res.data.serviceInfo.serviceCom);
            $("#tax").html(res.data.serviceInfo.serviceTaxCode);
            $("#dzdh").html(res.data.serviceInfo.serviceAddress+"-"+res.data.serviceInfo.servicePhone);
            $("#cyh").html(res.data.serviceInfo.serviceBank +"-"+res.data.serviceInfo.serviceAccount);


        }else {
            layer.msg(res.msg);
        }
    });

    //选择收件人 下拉框 数据显示
    var iniExpressReceiverList = function () {
        API.postAjax(sjrUrl,{}, function(result){
            selData = result.data;
            console.log("selData+"+selData);

            var _h = "<option value='|||'>请选择收件人</option>";

            for(var i =0; i<selData.length; i++){
                _h += "<option value='"+selData[i].mobile+"|"+selData[i].address+"|"+selData[i].recivePersonId+"'>"+selData[i].recivePersonName+"</option>"
            }
            $("#expressId").html(_h);

        });
    };
    //窗口打开加载收件人列表
    iniExpressReceiverList();
    //点击刷新收件人列表
    $("#expressId").mousedown(function () {
        // iniExpressReceiverList();
    });

    $("#submitBtn").click(function () {
    	$('#submitBtn').addClass("layui-btn-disabled").attr("disabled",true);
        var recivePersonName = $("#expressId").val().split("|")[2],
            billTypeId = $(".ui_fpClass").val(),
            taxableTotal = $("#invoiceAmount").val(),
            orderId = $("input[name='orderId']").val(),
            orderSource = $("input[name='orderSource']").val(),
            sellerCompanyName = $("#gmf").html(),
            billContent = $("input:radio[name='invoiceContent']:checked").val(),
            sellerId = $("input[name='sellerId']").val(),
            serviceId = $("input[name='serviceId']").val(),
            uploadId = $("input[name='uploadId']").val(),
            _data = {
                recivePersonName : recivePersonName,
                billTypeId : billTypeId,
                taxableTotal : taxableTotal,
                //orderId : orderId,     开票和上传充值记录关联
                orderSource : orderSource,
                sellerCompanyName : sellerCompanyName,
                billContent : billContent,
                sellerId : sellerId,
                serviceId : serviceId,
                uploadId : orderId
            };

        var _amount = $("#invoiceAmount").attr('data-amount');

        console.log("_amount = "+_amount);

        console.log("taxableTotal="+taxableTotal);

        console.log("recivePersonName+"+recivePersonName);


        if(recivePersonName == "" || recivePersonName == "undefined"){
            layer.msg('请选择收件人', {icon: 5});
            $('#submitBtn').removeClass("layui-btn-disabled").attr("disabled",false);
            return false;
        }


        if(billContent == null){
            layer.msg('请选择【货物或应税劳务、服务名称】后再提交！', {icon: 5});
            $('#submitBtn').removeClass("layui-btn-disabled").attr("disabled",false);
            return false;
        }

        if(parseFloat(taxableTotal) > parseFloat(_amount.replace(/,/g,""))){
            layer.msg('超过剩余开票金额，请重新输入', {icon: 5},function () {
                $("#invoiceAmount").focus();
            });
            $('#submitBtn').removeClass("layui-btn-disabled").attr("disabled",false);
            return false;
        }

        if(taxableTotal == ''){
            layer.msg('请输入开票金额后再提交！', {icon: 5});
            $('#submitBtn').removeClass("layui-btn-disabled").attr("disabled",false);
            return false;
        }
        API.postAjax(API.invoice.insSellerBill,_data,function (res) {
            if(res.code == 0){
                layer.alert('发票申请成功！', {
                }, function(){
                    var _url = '/index.html?#/page/invoice/apply.html';
                    console.log("url ="+ window.parent.location.href);
                    window.parent.parent.location.reload();
                    window.parent.parent.location.href = _url;
                });
            }

        });
    });

});

function iExpress(obj) {
    var $ = layui.jquery;
    var _s  = $(obj).val();
    _s = _s.split("|");
    $("#sjh").val(_s[0]);
    $("#sjdz").val(_s[1]);
}
function infCaps(money) {
    var fraction = ['角','分'];
    var digit = ['零','壹','贰','叁','肆','伍','陆','柒','捌','玖'];
    var unit = [['元','万','亿'],['','拾','佰','仟']];
    var head = money < 0?'欠':'';
    money = Math.abs(money);
    var s = '';
    for (var i = 0; i < fraction.length; i++) {
        s += (digit[Math.floor(money * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
    }
    s = s || '整';
    money = Math.floor(money);
    for (var i = 0; i < unit[0].length && money > 0; i++) {
        var p = '';
        for (var j = 0; j < unit[1].length && money > 0; j++) {
            p = digit[money % 10] + unit[1][j] + p;
            money = Math.floor(money / 10);
        }
        s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
    }
    var sum= head + s.replace(/(零.)*零元/,'元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整');

    return sum;
}
function money(obj) {
    var $ = layui.jquery;
    var money = $(obj).val();
    console.info();
    console.log("money="+money);
    /*var _amount = $("#invoiceAmount").attr('data-amount');

    if(money > _amount){
        layer.msg('超过剩余开票金额，请重新输入', {icon: 5},function () {
            $(obj).focus();
        });
    }

     */
    if(money.indexOf('.')>0){
        $(".xxje").html("￥"+API1.numFun(money));
    }else {

        $(".xxje").html("￥"+API1.numFun(money));
    }

    var sum = infCaps(money);

    $(".dxje").html(sum);

}

